<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form
          @submit.native.prevent
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="用户名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入用户名称"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input
              v-model="queryParams.phone"
              placeholder="请输入手机号码"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['system:user:export']"
              >批量导出</el-button
            >
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="userList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="编号" align="center" prop="id" />
          <el-table-column
            label="真实姓名"
            align="center"
            key="name"
            prop="name"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="用户昵称"
            align="center"
            key="nickName"
            prop="nickName"
          />
          <el-table-column
            label="手机号码"
            align="center"
            key="phone"
            prop="phone"
            width="120"
          />
          <el-table-column
            label="等级"
            align="center"
            key="score"
            prop="score"
          />
          <el-table-column
            label="性别"
            align="center"
            key="gender"
            prop="gender"
          >
            <template #default="scope">
              {{ scope.row.gender == "MALE" ? "男" : "女" }}
            </template>
          </el-table-column>
          <el-table-column
            label="现在积分"
            align="center"
            key="score"
            prop="score"
          />
          <el-table-column
            label="现有渡币"
            align="center"
            key="balance"
            prop="balance"
          />
          <el-table-column
            label="邀请码"
            align="center"
            key="inviteCode"
            prop="inviteCode"
          />
          <el-table-column
            label="推荐人"
            align="center"
            key="invitedBy"
            prop="invitedBy"
          />
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            width="170"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.gmtCreate) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="210"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <a
                href="javascript:;"
                style="
                  color: #358de5;
                  text-decoration: none;
                  margin-right: 10px;
                "
                @click="handleUpdate(scope.row, 1)"
                >查看</a
              >
              <a
                href="javascript:;"
                style="
                  color: #358de5;
                  text-decoration: none;
                  margin-right: 10px;
                "
                @click="handleUpdate(scope.row, 2)"
                >编辑</a
              >
              <a
                href="javascript:;"
                v-if="scope.row.disable == 0"
                style="
                  color: #f56c6c;
                  text-decoration: none;
                  margin-right: 10px;
                "
                @click="handleClose(scope.row)"
                >禁用</a
              >
              <a
                href="javascript:;"
                v-if="scope.row.disable == 1"
                style="
                  color: #00d669;
                  text-decoration: none;
                  margin-right: 10px;
                "
                @click="handleClose(scope.row)"
                >启用</a
              >
              <a
                href="javascript:;"
                style="
                  color: #358de5;
                  text-decoration: none;
                  margin-right: 10px;
                "
                @click="handleResetScore(scope.row)"
                >修改积分</a
              >
              <a
                href="javascript:;"
                style="
                  color: #358de5;
                  text-decoration: none;
                  margin-right: 10px;
                "
                @click="handleUserFamily(scope.row)"
                >家庭成员</a
              >
              <a
                href="javascript:;"
                style="
                  color: #358de5;
                  text-decoration: none;
                  margin-right: 10px;
                "
                @click="handleFamilyTree(scope.row)"
                >家谱成员</a
              >
              <a
                href="javascript:;"
                style="
                  color: #358de5;
                  text-decoration: none;
                  margin-right: 10px;
                "
                @click="handleInvited(scope.row)"
                >已邀请会员</a
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.size"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form
        @submit.native.prevent
        :model="form"
        :rules="rules"
        ref="userRef"
        label-width="80px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="头像" prop="avatarUrl">
              <el-upload
                ref="uploadRef"
                :action="baseUrl + '/oss/upload'"
                 :headers="headers"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-success="handleAvatarSuccess"
              >
                <el-avatar :size="80" :src="form.avatarUrl"></el-avatar>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input
                v-model="form.nickName"
                placeholder="请输入用户昵称"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入用户姓名"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户等级" prop="levelName">
              <el-input
                v-model="form.levelName"
                placeholder="请输入用户等级"
                maxlength="30"
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="积分" prop="score" required class="form-item">
              <el-input
                v-model="form.score"
                placeholder="请输入用户积分"
                maxlength="30"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="渡币" prop="balance">
              <el-input
                v-model="form.balance"
                placeholder="请输入用户渡币"
                maxlength="30"
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input
                v-model="form.phone"
                placeholder="请输入手机号码"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邀请码" prop="inviteCode">
              <el-input
                v-model="form.inviteCode"
                placeholder="请输入"
                maxlength="50"
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="form.gender" placeholder="请选择">
                <el-option
                  v-for="dict in sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会员过期时间" label-width="120">{{
              parseTime(form.membershipExpiryDate)
            }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer v-if="title !== '详情'">
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改积分 -->
    <el-dialog
      title="修改积分"
      v-model="changeScore"
      width="450px"
      append-to-body
    >
      <el-form
        @submit.native.prevent
        :model="editForm"
        ref="userRef"
        label-width="100px"
      >
        <el-form-item label="用户姓名" prop="name">
          <el-input
            v-model="editForm.name"
            placeholder="请输入用户姓名"
            readonly
          />
        </el-form-item>
        <el-form-item label="当前积分" prop="name">
          <el-input
            v-model="editForm.scored"
            placeholder="请输入当前积分"
            readonly
          />
        </el-form-item>
        <el-form-item label="积分调整" prop="name">
          <el-input-number
            v-model="editForm.score"
            placeholder="请输入积分"
            :min="1"
            @blur="handleChange"
          />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="调整后积分：">
              {{ editForm.score }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调整后等级：">
              {{ editForm.levelName }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input
            v-model="editForm.remark"
            type="textarea"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer v-if="title !== '详情'">
        <div class="dialog-footer">
          <el-button type="primary" @click="submitEditForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 已邀请会员 -->
    <el-dialog
      title="邀请会员"
      v-model="showInvite"
      width="800px"
      append-to-body
    >
    <div class="clearfix">
          <span>{{inviteName+"已邀请会员 （共"+invitedTotal+"人，付费会员 8 人）"}}</span>
     </div>
      <el-card>
        <div class="box-card">
          <el-table v-loading="loading" :data="invitedList">
            <el-table-column
              label="用户昵称"
              align="center"
              key="nickName"
              prop="nickName"
            />
            <el-table-column
              label="真实姓名"
              align="center"
              key="name"
              prop="name"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="手机号码"
              align="center"
              key="phone"
              prop="phone"
              width="120"
            />
            <el-table-column
              label="等级"
              align="center"
              key="score"
              prop="score"
            />
            <el-table-column
              label="性别"
              align="center"
              key="gender"
              prop="gender"
            >
              <template #default="scope">
                {{ scope.row.gender == "MALE" ? "男" : "女" }}
              </template>
            </el-table-column>
            <el-table-column
              label="现在积分"
              align="center"
              key="score"
              prop="score"
            />
            <el-table-column
              label="现有渡币"
              align="center"
              key="balance"
              prop="balance"
            />
          </el-table>
          <pagination
            v-show="invitedTotal > 0"
            :total="invitedTotal"
            v-model:page="invitedParams.pageNum"
            v-model:limit="invitedParams.pageSize"
            @pagination="getInviteList"
          />
        </div>
      </el-card>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import {
  queryUserPage,
  editUser,
  editScore,
  queryLevelName,
  userExport,
} from "@/api/member";
import { getToken } from "@/utils/auth";
const headers = ref({ Authorization: "Bearer " + getToken() });
const router = useRouter();
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const { proxy } = getCurrentInstance();
const sys_user_sex = [
  {
    label: "男",
    value: "MALE",
  },
  {
    label: "女",
    value: "FEMALE",
  },
];
const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const changeScore = ref(false);

const invitedList = ref([]);
const showInvite = ref(false);
const invitedTotal = ref(0);
const inviteCode= ref(null);
const inviteName= ref(null);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {
    id: undefined,
    name: undefined,
    nickName: undefined,
    phone: undefined,
    description: undefined,
    gender: undefined,
    avatarUrl: undefined,
    score: 0,
    balance: undefined,
    levelName: undefined,
    remark: undefined,
  },
  editForm: {
    id: undefined,
    name: undefined,
    scored: 0,
    score: 0,
    levelName: undefined,
    remark: undefined,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 1000,
    name: undefined,
    phone: undefined,
  },
  invitedParams: {
    pageNum: 1,
    pageSize: 1000,
  },
  rules: {
    name: [
      { required: true, message: "用户名称不能为空", trigger: "blur" },
      {
        min: 2,
        max: 20,
        message: "用户名称长度必须介于 2 和 20 之间",
        trigger: "blur",
      },
    ],
    nickName: [
      { required: true, message: "用户昵称不能为空", trigger: "blur" },
    ],
    phone: [
      {
        required: true,
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
  },
});

const { queryParams, form, rules, editForm ,invitedParams} = toRefs(data);

/** 查询用户列表 */
const getList = () => {
  loading.value = true;
  queryUserPage({
    ...queryParams.value,
  }).then((res) => {
    loading.value = false;
    userList.value = res.rows;
    total.value = Number(res.total);
  });
};

/** 头像上传 */
const handleAvatarSuccess = (res, file) => {
  form.value.avatarUrl = res.url;
};

const beforeAvatarUpload = (file) => {
  const isFileType = ["image/jpeg", "image/png"].indexOf(file.type) < 0;
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (isFileType) {
    ElMessage.error("上传头像图片格式不正确!");
  }

  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
  }
  return !isFileType && isLt2M;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  proxy.resetForm("queryRef");
  queryParams.value = {
    pageNum: 1,
    pageSize: 1000,
    name: undefined,
    phone: undefined,
  };
  handleQuery();
};
/** 禁止按钮操作 */
const handleClose = (row) => {
  const userName = row.nickName;
  proxy.$modal
    .confirm(
      row.disable == 0
        ? "是否确认要禁用"
        : "是否确认要启用" + "“" + userName + "”用户？"
    )
    .then(() => {
      return editUser({
        id: row.id,
        disable: row.disable == 0 ? 1 : 0,
      });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess(row.disable == 0 ? "禁用成功" : "启用成功");
    })
    .catch(() => {});
};

/** 导出按钮操作 */
const handleExport = async () => {
  proxy.$modal.loading("文件导出中，请稍候...");
  let result = await userExport();
  const blob = new Blob([result]);
  let link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = "用户列表_" + new Date().getTime() + ".xlsx";
  link.click();
  proxy.$modal.closeLoading();
};

/** 查看对应家庭成员 */
const handleUserFamily = (row) => {
  router.push("/member/list-member/user/" + row.id);
};

/** 查看对应家谱成员 */
const handleFamilyTree = (row) => {
  router.push("/member/list-tree/user/" + row.id);
};


const handleInvited = (row) => {
  inviteCode.value=row.id
  inviteName.value=row.name
  getInviteList()
};
const getInviteList =()=>{
  queryUserPage({
    invitedBy:inviteCode.value
  }).then((res) => {
    loading.value = false;
    invitedList.value = res.rows;
    invitedTotal.value = Number(res.total);
    showInvite.value=true
  });
}

/** 修改积分 */
const handleResetScore = (row) => {
  editForm.value = {
    id: row.id,
    name: row.name,
    scored: row.score,
    score: row.score,
    levelName: undefined,
    remark: undefined,
  };
  changeScore.value = true;
};
/** 选择条数  */
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const handleChange = (e) => {
  if (editForm.value.score > 1) {
    queryLevelName(editForm.value.score).then((res) => {
      editForm.value.levelName = res.data.levelName;
    });
  }
};

/** 重置操作表单 */
const reset = () => {
  form.value = {
    id: undefined,
    name: undefined,
    nickName: undefined,
    phone: undefined,
    description: undefined,
    gender: undefined,
    avatarUrl: undefined,
    score: 0,
    balance: undefined,
    levelName: undefined,
    remark: undefined,
  };
  proxy.resetForm("userRef");
};

/** 取消按钮 */
const cancel = () => {
  open.value = false;
  changeScore.value = false;
  reset();
};

/** 修改按钮操作 */
const handleUpdate = (row, type) => {
  reset();
  title.value = type == 1 ? "详情" : "编辑";
  form.value = {
    ...row,
  };
  open.value = true;
};

/** 提交按钮 */
const submitForm = () => {
  proxy.$refs["userRef"].validate((valid) => {
    if (valid) {
      editUser(form.value).then((response) => {
        proxy.$modal.msgSuccess("编辑成功");
        open.value = false;
        getList();
      });
    }
  });
};

/** 提交按钮 */
const submitEditForm = () => {
  proxy.$refs["userRef"].validate((valid) => {
    if (valid) {
      editScore({
        id: editForm.value.id,
        remark: editForm.value.remark,
        score: editForm.value.score,
      }).then((res) => {
        proxy.$modal.msgSuccess("修改成功");
        changeScore.value = false;
        getList();
      });
    }
  });
};

getList();
</script>
<style lang='scss' scoped>
.box-card{
  padding:20px;
  position:relative;
}
  .clearfix{
  padding:20px;
  font-weight:500;
  color:#333;
  font-size: 20px;
}

</style>
